package org.jash.shop2201.user

import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import org.jash.shop2201.BR
import org.jash.shop2201.databinding.ActivityLoginBinding
import org.jash.shop2201.mvvm.BaseActivity
import org.jash.shop2201.utils.StoreUtils
import org.jash.shop2201.utils.token

private val r1 = ".{8,}".toRegex()
private val r2 = "^(?=.*\\d.*\$)(?=.*[a-z].*\$)(?=.*[A-Z].*\$)(?=.*[!,?#.].*\$).*$".toRegex()
@Route(path = "/shop/login")
class LoginActivity : BaseActivity<ActivityLoginBinding, LoginViewModel>() {
    val map by lazy { mutableMapOf<String,String>("username" to StoreUtils.getString("username", ""), "password" to StoreUtils.getString("password", "")) }
    override fun initData() {
        viewModel.userLiveData.observe(this) {
            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
            token = it.token
            map.forEach(StoreUtils::save)
            ARouter.getInstance().build("/shop/main").navigation()
            finish()
        }
    }

    override fun initView() {
        binding.user = map
        binding.login.setOnClickListener {
//            if (binding.username.isErrorEnabled) {
//                Toast.makeText(this, binding.username.error, Toast.LENGTH_SHORT).show()
//                return@setOnClickListener
//            }
//            if (binding.password.isErrorEnabled) {
//                Toast.makeText(this, binding.password.error, Toast.LENGTH_SHORT).show()
//                return@setOnClickListener
//            }
            viewModel.login(map)
        }
        binding.password.editText?.addTextChangedListener {
//            binding.password.error = "密码必须大于6位"
//            binding.password.isErrorEnabled = (map["password"]?.length ?: 0) < 6
            binding.cb1.isChecked = r1.matches(map["password"] ?: "")
            binding.cb2.isChecked = r2.matches(map["password"] ?: "")
        }
    }

}